//
//  UIColor+XXExtension.m
//  SHWheel
//
//  Created by YYKJ on 2020/10/16.
//  Copyright © 2020 YYKJ. All rights reserved.
//

#import "UIColor+XXExtension.h"

@implementation UIColor (XXExtension)

+ (UIColor *)xx_randomColor {
    return  [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
}

+ (CGFloat)_colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length
{
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

+ (UIColor *)xx_colorWithHexString: (NSString *) hexString
{
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#"withString: @""] uppercaseString];
    //因为下面用了default，所以需要初始化
    CGFloat alpha = 0.0, red = 0.0, blue = 0.0, green = 0.0;
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self _colorComponentFrom: colorString start: 0 length: 1];
            green = [self _colorComponentFrom: colorString start: 1 length: 1];
            blue  = [self _colorComponentFrom: colorString start: 2 length: 1];
            break;
        case 4: // #ARGB
            alpha = [self _colorComponentFrom: colorString start: 0 length: 1];
            red   = [self _colorComponentFrom: colorString start: 1 length: 1];
            green = [self _colorComponentFrom: colorString start: 2 length: 1];
            blue  = [self _colorComponentFrom: colorString start: 3 length: 1];
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = [self _colorComponentFrom: colorString start: 0 length: 2];
            green = [self _colorComponentFrom: colorString start: 2 length: 2];
            blue  = [self _colorComponentFrom: colorString start: 4 length: 2];
            break;
        case 8: // #AARRGGBB
            alpha = [self _colorComponentFrom: colorString start: 0 length: 2];
            red   = [self _colorComponentFrom: colorString start: 2 length: 2];
            green = [self _colorComponentFrom: colorString start: 4 length: 2];
            blue  = [self _colorComponentFrom: colorString start: 6 length: 2];
            break;
        default:
            //            [NSExceptionraise:@"Invalid color value"format: @"Color value %@ is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
            break;
    }
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

@end
